 

let target = null
// 降低任务的优先级 不会影响到页面的首屏渲染速度
// 重传机制，首次发送失败，那下次发送的时机在页面关闭之前发送
// 发送数据无跨域限制

class Micro{
      constructor(userid,sendip){
           this.userid = userid;
           this.sendip = sendip; 
           target = this;
           // 监听
           let PVdata = localStorage.getItem('PV_DATA')
           if(PVdata){
              return false; 
           }
           localStorage.setItem('PV_DATA',''); 
          //  降低任务执行的优先级
           requestIdleCallback(()=>{
            this.getBrowserInfo();
            this.getIP().then(res=>{ 
                this.SelfIp = res;
                console.log(this.composefn([this.getBrowserInfo,this.builder,this.sender],res))
            },err=>{
                alert('网络错误！');
            }); 
           })
           
        //    页面卸载前期 将状态进行移除
        window.addEventListener('unload',()=>{
              let PVdata2 = localStorage.getItem('PV_DATA');
              //如果出现这种情况说明 可能是网络失败无法上报
              if(PVdata2.length>10){
                // 回传效果
                this.logdata()
              } 
        },false)
        // 网络在线的情况
        window.addEventListener('online',()=>{
            // 暂时扩展
        })
      }
      //所有高阶操作使用管道处理 
      composefn(arr,data){
            return arr.reduce((pre,item)=>item(pre),data)
      }
      filterdate(e){
           let data = new Date(e);
           let y = data.getFullYear();
           let m = data.getMonth()+1;
           let d = data.getDate();
           let h = data.getHours();
           let ms = data.getMinutes();
           let s = data.getSeconds();
           return `${y}-${m<10?('0'+m):m}-${d<10?('0'+d):d} ${h<10?('0'+h):h}:${ms<10?('0'+ms):ms}`;
      }
      getBrowserInfo(ip){
        let obj = {}; 
             if(window.navigator){
                let user = window.navigator;
                let times = new Date().getTime();
                let _this = this;
            
                   obj = {
                    // 2023-01-01 09:09
                    start_time:target.filterdate(times),
                    appCodeName:user.appCodeName, // 
                    appVersion:user.appVersion,// 版本
                    effectiveType:user.effectiveType, // 网络环境
                    language:user.language, // 语言
                    platform:user.platform, // 操作系统
                    vendor:user.vendor,
                    url:window.location.pathname,
                    ip
                   }
             }
             return obj;
      }
      /**
       * 
*   - 用户
    - 游客无token - 指纹
    - 常规用户 token - 用户id 
    - 访问时间 - 
    - 页面Url - 
    - 设备信息 - 
       * @param {*} data 
       */
       getIP() {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.open('GET', 'https://api.ipify.org?format=json'); 
          xhr.onload = () => { 
            if (xhr.status >= 200 && xhr.status < 300) {
              resolve(JSON.parse(xhr.responseText).ip);
            } else {
              reject('获取 IP 失败');
            }
          }; 
          xhr.onerror = () => reject('获取 IP 失败'); 
          xhr.send();
        });
      }
      builder(data){
            let obj = {
                userid:target.userid,
                type:'PV',
                ...data  
            }
            return obj;     
      }
      logdata(data){
        let str = `userid=${target.getempty(data.userid)}&&appCodeName=${target.getempty(data.appCodeName)}&&appVersion=${target.getempty(data.appVersion)}&&language=${target.getempty(data.language)}&&platform=${data.platform}&&vendor=${data.vendor}&&url=${'xxx'}&&ip=${data.ip}`
      
        navigator.sendBeacon(`${this.sendip}?${str}`);
      }
      getempty(e){
        return e==''?'null':e
      }
    // 重传，在页面彻底关闭之前 将数据传递过去
      sender(data){    
          let str = `userid=${target.getempty(data.userid)}&&appCodeName=${target.getempty(data.appCodeName)}&&appVersion=${target.getempty(data.appVersion)}&&language=${target.getempty(data.language)}&&platform=${data.platform}&&vendor=${data.vendor}&&url=${'xxx'}&&ip=${data.ip}`
          console.group('MICRO上报SDK')
           return (new Image()).src=`${target.sendip}?${str}`;
      }
}  
const MicroInstace = (userid,sendip)=>{
     return new Micro(userid,sendip)
}
export default MicroInstace;





 